// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
const log = cloud.log()
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let unionid = wxContext.FROM_UNIONID || wxContext.UNIONID
    let openId = wxContext.OPENID
    let res = await db.collection("users").where({
        _unionid: unionid
    }).get()
    if(!unionid || !openId){
        log(`Cannot get user authorized code like unionid or openid`)
        return{
            code:401,
            msg:"Cannot get user authorized code like unionid or openid"
        }
    }
    if (res.data.length == 0 && openId!=undefined) {
        log(`add a new user that openid is:${openId}`)
        let result =await db.collection("users").add({
            data: [{
                _unionid: unionid,
                _openid: openId,
                createTime: new Date(),
                phone:event.phone
            }]
        })
        if (result.data.length >= 0) {
            return {
                code: 200,
                msg: "resiger success!"
            }
        } else {
            log(`error while insert a record that unionid is ${wxContext.UNIONID}`)
            return{
                code:401,
                msg:"The server has an error"
            }
        }
    } else {
        return {
            code: 200,
            msg: "the user already exist or login platform is not minprogram ,but is intendeed for other authorized applications!"
        }
    }
}